//
//  CZUploadTaskPicViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/2/18.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZUploadTaskPicViewController.h"
#import "CZTaskUploadPicCell.h"
#import "CZMyTaskImageCell.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "CZUploadTaskCell.h"
#import "ELCImagePickerController.h"

static NSString * const task_pic_cell = @"task_pic_cell";

@interface CZUploadTaskPicViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, ELCImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
//@property (weak, nonatomic) IBOutlet UITableView *uploadPicTableView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *originalImageArray;
@property (nonatomic, strong) NSMutableArray *imgLocalUrlArray;

@end

@implementation CZUploadTaskPicViewController

- (NSMutableArray *)originalImageArray {
    if (!_originalImageArray) {
        _originalImageArray = [[NSMutableArray alloc] init];
    }
    return _originalImageArray;
}

- (NSMutableArray *)imgLocalUrlArray {
    if (!_imgLocalUrlArray) {
        _imgLocalUrlArray = [[NSMutableArray alloc] init];
    }
    return _imgLocalUrlArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"上传图片";
    //1.创建一个布局对象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    //列距 同一行中，元素之间的距离
    flowLayout.minimumInteritemSpacing = 10;
    //行距
    flowLayout.minimumLineSpacing = 10;
    //分区内边距
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    //itemSize 我们设置为一行三列
    CGFloat itemWidth = (Main_Screen_Width - 5 * 10) / 3.0;
    //注意：item的宽高必须要提前算好。
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
    
    //设置滚动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    //    flowLayout.itemSize = CGSizeMake(335, 200);
    
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, Main_Screen_Width, Main_Screen_Height - 40 - 64) collectionViewLayout:flowLayout];
    
    //    [collectionView registerClass:[CZUploadTaskCell class] forCellWithReuseIdentifier:upload_cell];
    [collectionView registerNib:[UINib nibWithNibName:@"CZUploadTaskCell" bundle:nil] forCellWithReuseIdentifier:task_pic_cell];
    
    //    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
//    [collectionView registerNib:[UINib nibWithNibName:@"CZTaskInfoCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
//    
//    [collectionView registerNib:[UINib nibWithNibName:@"CZPicCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header1"];
//    self.collectionView = collectionView;
    
    //注册区尾
    //    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    
    
    //设置数据源和代理
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = GLOBAL_BACKGROUND_COLOR;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //默认为1
    return self.picArray.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CZUploadTaskCell *cell = (CZUploadTaskCell *)[collectionView dequeueReusableCellWithReuseIdentifier:task_pic_cell forIndexPath:indexPath];
    cell.iconView.contentMode = UIViewContentModeScaleAspectFill;
    if (indexPath.row != self.picArray.count) {
        if ([self.picArray[indexPath.row] isKindOfClass:[UIImage class]]) {
            cell.iconView.image = self.picArray[indexPath.row];
        } else {
            NSDictionary *dic = self.picArray[indexPath.row];
            cell.iconView.yy_imageURL = [NSURL URLWithString:dic[@"pic"]];
        }
        cell.deleteBtn.hidden = NO;
        [cell.deleteBtn addTarget:self action:@selector(deletePic:) forControlEvents:(UIControlEventTouchUpInside)];
    } else {
        cell.iconView.image = [UIImage imageNamed:@"icon_puls"];
        cell.iconView.contentMode = UIViewContentModeCenter;
        cell.iconView.backgroundColor = mRGBColor(150, 150, 150);
        cell.deleteBtn.hidden = YES;
    }
    cell.backgroundColor = ThemeColor;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.picArray.count) {
        [self chooseImage];
    }
}


#pragma mark - 选择图片
- (void)chooseImage {
    
    UIAlertController *alertController = [[UIAlertController alloc] init];
    UIAlertAction *photoLibraryAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self showImagePicker];
    }];
    
    //访问受限
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"照相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"摄像头访问受限" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertC animated:YES completion:nil];
            UIAlertAction * action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertC addAction:action];
        } else if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController *imageaPicker = [[UIImagePickerController alloc] init];
            UIImagePickerControllerSourceType sourceTypePhoto = UIImagePickerControllerSourceTypeCamera;
            imageaPicker.sourceType = sourceTypePhoto;
            imageaPicker.delegate = self;
            [self presentViewController:imageaPicker animated:YES completion:^{
                
            }];
        }
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:photoLibraryAction];
    [alertController addAction:cameraAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage* image = [[UIImage alloc] init];
    image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self.originalImageArray addObject:[info objectForKey:UIImagePickerControllerOriginalImage]];
    [self.imgLocalUrlArray addObject:@""];
    [self updateUI];

}


#pragma mark- 删除图片
- (void)deletePic:(UIButton *)button {
    CZUploadTaskCell *cell = (CZUploadTaskCell *)button.superview.superview;
    NSInteger index = [self.collectionView indexPathForCell:cell].row;
    id image = self.picArray[index];
    if ([image isKindOfClass:[UIImage class]]) {
        NSInteger imgIndex = [self.originalImageArray indexOfObject:image];
        [self.imgLocalUrlArray removeObjectAtIndex:imgIndex];
        [self.originalImageArray removeObject:image];
    }
    [self.picArray removeObjectAtIndex:index];
    [self.collectionView reloadData];
    if (self.callBack) {
        self.callBack();
    }
}

- (void)showImagePicker {
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    
    elcPicker.maximumImagesCount = 100; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie]; //Supports image and movie types
    
    elcPicker.imagePickerDelegate = self;
    [self presentViewController:elcPicker animated:YES completion:nil];
}

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info {
    [self dismissViewControllerAnimated:YES completion:nil];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (NSDictionary *dict in info) {
            if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
                
                NSString *url = [dict objectForKey: UIImagePickerControllerReferenceURL];
                if (![self.imgLocalUrlArray containsObject:url]) {
                    [self.originalImageArray addObject:[dict objectForKey:UIImagePickerControllerOriginalImage]];
                    [self.imgLocalUrlArray addObject:url];
                }
                
            } else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){
                
                if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                    NSString *url = [dict objectForKey: UIImagePickerControllerReferenceURL];
                    if (![self.imgLocalUrlArray containsObject:url]) {
                        [self.originalImageArray addObject:[dict objectForKey:UIImagePickerControllerOriginalImage]];
                        [self.imgLocalUrlArray addObject:url];
                    }
                }
            } else {
                NSLog(@"Uknown asset type");
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateUI];
        });
    });
    
    
}

- (void)updateUI {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSMutableArray *urlArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < self.picArray.count; i ++) {
            if ([self.picArray[i] isKindOfClass:[NSDictionary class]]) {
                [urlArray addObject:self.picArray[i]];
            }
        }
        self.picArray = urlArray;
        for (UIImage *img in self.originalImageArray) {
            [self.picArray addObject:img];
        }
        [self.collectionView reloadData];
    });
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 上传提交到阿里云
- (IBAction)addPic:(UIButton *)sender {
    if (self.originalImageArray.count < 1) {
        [SVProgressHUD showInfoWithStatus:@"请选择上传图片"];
        return;
    }
    [SVProgressHUD show];
    __block NSInteger i = self.originalImageArray.count;
    __block int lossNum = 0;
    
    for (UIImage *image in self.originalImageArray) {
        NSData *compressData = UIImageJPEGRepresentation(image, 0.75);
        CZNsjHelper *helper = [[CZNsjHelper alloc] init];
        [helper uploadObjectSyncWithObjectKey:@"task_pic" fileData:compressData successStatus:nil errorStatus:@"上传失败" completion:^(NSString *urlString) {
            i --;
            
            [self.picArray removeObject:image];
            [self.picArray addObject:@{@"pic" : urlString}];
            if (i == 0) {
                [SVProgressHUD showSuccessWithStatus:@"图片上传成功"];
                if (self.callBack) {
                    self.callBack();
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        } fail:^{
            i++;
            lossNum ++;
            [self.picArray removeObject:image];
            if (i == 0) {
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%d张图片上传失败", lossNum]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.collectionView reloadData];
                });
                
            }
        }];

    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
